package com.hzy.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Scope;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

// 交给spring容器管理
@Component
@Scope
@Aspect
@Order(1)
public class LockAop {

    Lock lock = new ReentrantLock(true);

    @Pointcut("@annotation(com.hzy.annotation.ServiceLock)")
    public void lockAspect(){
        System.out.println("锁切入");
    }
    @Around("lockAspect()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object obj = null;
        System.out.println("环绕锁");

        // 加锁
        lock.lock();


        try {
            //执行业务
            obj = joinPoint.proceed();

            // 此处不捕获异常，直接抛出，防止Service的异常Controller捕获不到
        } finally {
            // 业务执行结束后，释放锁
            lock.unlock();
        }

        return obj;
    }


}
